package com.factory.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.rest.manager.WebRTCManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/rest")
@Slf4j
public class IndexController {

    @Value("${jiexun.upload.dir}")
    private String uploadDir;

    /**
     * 前端获取图片的接口
     *
     * @throws
     * @Title: getImage
     * @Description:
     * @param: @param id
     * @param: @return
     * @return: byte[]
     */
    @RequestMapping(value = "/image/{addres}", produces = MediaType.IMAGE_JPEG_VALUE, method = RequestMethod.GET)
    public void getImage(HttpServletResponse response, @PathVariable("addres") String addres) {
        log.info("前端获取图片的接口,{}",addres);
        addres = new String(Base64.getUrlDecoder().decode(addres));
        addres = addres.replaceAll("%5C","/");
        log.debug("解码后的地址,{}",addres);
        FileInputStream fis = null;
        byte[] bytes = new byte[2048];

        try {

            ServletOutputStream outputStream = response.getOutputStream();
            fis = new FileInputStream(uploadDir + addres);
            while (fis.read(bytes) != -1){
                outputStream.write(bytes);
            }
            outputStream.flush();
        } catch (FileNotFoundException e) {
            log.error("文件不存在,{}", e);
        } catch (IOException e) {
            log.error("读取文件异常,{}", e);
        } finally {
            try {
                if (null != fis)
                    fis.close();
            } catch (IOException e) {
                log.error("关闭读取文件io流异常,{}", e);
            }
        }
    }


    /**
     * 用户上传文件
     * @param file
     * @return
     */
    @PostMapping("/index/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("文件不能为空");
        }

        String type = file.getOriginalFilename();
        type = type.substring(type.lastIndexOf("."));

        String filePath = "temp", fileName = StringUtil.getUUID() + type, picturePath = filePath + File.separator + fileName;

        try {
            file.transferTo(new File(uploadDir + picturePath));
        } catch (IOException e) {
            log.error(e.toString(), e);
            return Result.fail(null, "上传失败", 500);
        }

        return Result.success(picturePath, "上传成功");
    }

    /**
     * 文件下载接口
     *
     * @throws
     * @Description:
     * @param: params
     * @return: byte[]
     */
    @GetMapping(value = "/index/download/{address}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void download(HttpServletResponse response, @PathVariable("address") String address) {
        log.info("文件下载接口,{}",address);
        address = new String(Base64.getUrlDecoder().decode(address));
        address = address.replaceAll("%5C","/");
        log.debug("解码后的地址,{}",address);

        File file = new File(uploadDir + File.separator + address);
        if(file.exists()){

            FileInputStream fis = null;
            byte[] bytes = new byte[2048];
            try {
                ServletOutputStream outputStream = response.getOutputStream();
                fis = new FileInputStream(file);
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                while (fis.read(bytes) != -1){
                    outputStream.write(bytes);
                }
                outputStream.flush();
            } catch (FileNotFoundException e) {
                log.error("文件不存在,{}", e);
            } catch (IOException e) {
                log.error("读取文件异常,{}", e);
            } finally {
                try {
                    if (null != fis)
                        fis.close();
                } catch (IOException e) {
                    log.error("关闭读取文件io流异常,{}", e);
                }
            }
        }
    }

    /**
     * 发送webrtc信令数据
     * @param jsonObject
     * @return
     */
    @PostMapping("/index/webRtc")
    public Result webRtc(@RequestBody JSONObject jsonObject){
        log.info("发送到webRtc客户端数据");

        if(!jsonObject.containsKey("toUserId")){
            return Result.fail("toUserId not null");
        }

        WebRTCManager.sendMessage(jsonObject.getString("toUserId"), jsonObject.toJSONString());

        return Result.success(null);
    }

    /**
     * 发送设备状态数据
     * @param jsonObject
     * @return
     */
    @PostMapping("/index/deviceStatus")
    public Result deviceStatus(@RequestBody JSONObject jsonObject){
        log.info("发送到webRtc客户端数据");

        if(!jsonObject.containsKey("toUserId")){
            return Result.fail("toUserId not null");
        }

        WebRTCManager.sendMessage(jsonObject.getString("toUserId"), jsonObject.toJSONString());

        return Result.success(null);
    }
}
